package homework.day01.mapper;

import homework.day01.pojo.User;
import homework.day01.util.IDBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Component
public class UserMapper implements IUserMapper {
    @Autowired
    private IDBUtil dbUtil;
    @Override
    public int insert(User user) {
        System.out.println("正在注册中....");
        String sql = "INSERT INTO user(username, password, nickname, age) " +
                "VALUES (?,?,?,?);";
        try(Connection connection = dbUtil.getConnection()) {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNickname());
            ps.setInt(4,user.getAge());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public void select(String username, String password) {
        System.out.println("信息校对中....");
        String sql = "SELECT username,password " +
                "FROM user " +
                "WHERE username = ? AND password = ?;";
        try(Connection connection = dbUtil.getConnection()) {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                System.out.println("尊敬的"+username+"用户，您已成功登录，欢迎使用本网站！");
            }else {
                System.out.println("用户名或密码错误，请重新输入！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


}
